package org.apache.lucene.ocean.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.lucene.util.UnicodeUtil;

/**
 * Encodes VLong, VInt and String using the default Lucene formats from IndexOutput
 */
public class VDataOutputStream extends DataOutputStream {
  private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result();
  
  public VDataOutputStream(OutputStream output) {
    super(output);
  }
  
  public void writeString(String s) throws IOException {
    UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8Result);
    writeVInt(utf8Result.length);
    write(utf8Result.result, 0, utf8Result.length);
  }
  
  public void writeVLong(long i) throws IOException {
    while ((i & ~0x7F) != 0) {
      writeByte((byte)((i & 0x7f) | 0x80));
      i >>>= 7;
    }
    writeByte((byte)i);
  }
  
  public void writeVInt(int i) throws IOException {
    while ((i & ~0x7F) != 0) {
      writeByte((byte)((i & 0x7f) | 0x80));
      i >>>= 7;
    }
    writeByte((byte)i);
  }
}
